// content.js - Automa风格选择器 + 工作流录制功能 + 数据抓取功能
let isExtensionValid = true;
let hoverHighlight = null;
let isHoverMode = false;
let isRecordingMode = false;
let isDataExtractionMode = false;
let currentHoveredElement = null;
let workflowRecorder = null;
let dataExtractor = null;
let lastUrl = window.location.href; // For navigation detection
let navigationIntervalId = null; // To clear the navigation interval

// 工作流录制器类
class WorkflowRecorder {
  constructor() {
    this.actions = [];
    this.startTime = Date.now();
    this.lastActionTime = this.startTime;
    this.nodeCounter = 1;
    this.currentUrl = window.location.href;
    this.formInputs = new Map(); // 跟踪表单输入状态
    this.pendingInputs = new Map(); // 等待完成的输入
    this.pendingInputClicks = new Map(); // 等待确认的输入框点击
  }

  // 添加动作到录制序列
  addAction(actionType, data) {
    const currentTime = Date.now();
    const timeSinceStart = currentTime - this.startTime;
    const timeSinceLastAction = currentTime - this.lastActionTime;

    const action = {
      id: `${actionType}-${this.nodeCounter++}`,
      type: actionType,
      timestamp: timeSinceStart,
      delay: timeSinceLastAction,
      data: data,
      url: window.location.href
    };

    this.actions.push(action);
    this.lastActionTime = currentTime;

    // 发送到侧边栏显示
    sendEvent({
      type: 'workflow_action_recorded',
      action: action,
      totalActions: this.actions.length
    });

    console.log('录制动作:', action);
  }

  // 处理页面导航
  recordNavigation(url, isInitialNavigation = false) {
    if (url !== this.currentUrl) {
      // 检查是否是由提交按钮或表单操作触发的导航
      const lastAction = this.actions[this.actions.length - 1];
      const timeDiff = Date.now() - this.lastActionTime;
      
      // 更严格的提交导航检测
      const isSubmitNavigation = lastAction && 
                                (
                                  // 点击提交按钮导致的导航
                                  (lastAction.type === 'click_element' && 
                                   lastAction.data && 
                                   lastAction.data.parameters &&
                                   lastAction.data.parameters.isSubmitButton) ||
                                  
                                  // 在输入框中按Enter键导致的导航（虽然我们没有记录Enter，但可能存在）
                                  (lastAction.type === 'input_text' && 
                                   lastAction.data &&
                                   lastAction.data.parameters &&
                                   lastAction.data.parameters.pressEnter)
                                ) &&
                                timeDiff < 10000; // 增加到10秒的时间窗口
      
      // 检查是否是由于页面内容变化导致的URL变化（如AJAX导航）
      const isSPANavigation = url.includes('#') || 
                             (this.currentUrl && url.startsWith(this.currentUrl.split('?')[0])) ||
                             (this.currentUrl && this.currentUrl.startsWith(url.split('?')[0]));
      
      console.log('导航检查:', {
        url: url,
        currentUrl: this.currentUrl,
        lastAction: lastAction,
        isSubmitNavigation: isSubmitNavigation,
        isSPANavigation: isSPANavigation,
        timeDiff: timeDiff,
        isInitialNavigation: isInitialNavigation
      });
      
      // 只记录以下情况的导航：
      // 1. 初始导航（录制开始时）
      // 2. 用户主动导航（非提交按钮、非SPA内导航）
      const shouldRecord = isInitialNavigation || (!isSubmitNavigation && !isSPANavigation);
      
      if (shouldRecord) {
        this.addAction('navigate', {
          label: `导航到 ${url}`,
          parameters: {
            url: url,
            waitFor: 'load',
            timeout: 30000
          }
        });
        console.log('记录导航动作');
      } else {
        console.log('忽略自动导航:', {
          reason: isSubmitNavigation ? '提交按钮导致' : 'SPA内导航',
          isSubmitNavigation,
          isSPANavigation
        });
      }
      
      this.currentUrl = url;
    }
  }

  // 处理点击事件
  recordClick(element, event) {
    const selector = getCSSSelector(element);
    const xpath = getXPath(element);
    
    // 检查是否是表单输入元素
    const isFormInput = (element.tagName === 'INPUT' && 
                        ['text', 'email', 'password', 'search', 'tel', 'url', 'number'].includes(element.type)) ||
                       element.tagName === 'TEXTAREA';
    
    // 如果是输入框，标记为待处理的点击，但不设置超时记录
    // 这个点击只是为了给后续的输入操作提供时间戳
    if (isFormInput) {
      this.pendingInputClicks.set(element, {
        timestamp: Date.now(),
        selector: selector,
        xpath: xpath
      });
      
      // 不再设置超时记录，输入框的激活点击会被忽略
      return;
    }
    
    // 检查是否是提交按钮，如果是，标记可能触发导航
    const isSubmitButton = element.type === 'submit' || 
                          element.tagName === 'BUTTON' && element.form ||
                          (element.tagName === 'INPUT' && element.type === 'submit');
    
    this.addAction('click_element', {
      label: `点击 ${element.tagName}${element.id ? '#' + element.id : ''}`,
      parameters: {
        selector: selector,
        selectorType: 'css',
        xpath: xpath,
        waitForElement: true,
        timeout: 10000,
        clickType: 'single',
        coordinates: { x: 0, y: 0 },
        isSubmitButton: isSubmitButton
      }
    });
  }
  
  // 记录输入框点击（当确定不会有输入操作时）
  recordInputClick(element) {
    const pendingClick = this.pendingInputClicks.get(element);
    if (!pendingClick) return;
    
    const timeSinceStart = pendingClick.timestamp - this.startTime;
    const timeSinceLastAction = pendingClick.timestamp - this.lastActionTime;
    
    const action = {
      id: `click_element-${this.nodeCounter++}`,
      type: 'click_element',
      timestamp: timeSinceStart,
      delay: timeSinceLastAction,
      data: {
        label: `点击 ${element.tagName}${element.id ? '#' + element.id : ''}`,
        parameters: {
          selector: pendingClick.selector,
          selectorType: 'css',
          xpath: pendingClick.xpath,
          waitForElement: true,
          timeout: 10000,
          clickType: 'single',
          coordinates: { x: 0, y: 0 },
          isSubmitButton: false
        }
      },
      url: window.location.href
    };
    
    this.actions.push(action);
    this.pendingInputClicks.delete(element);
    
    // 发送到侧边栏显示
    sendEvent({
      type: 'workflow_action_recorded',
      action: action,
      totalActions: this.actions.length
    });
  }

  // 处理智能文本输入（在失去焦点时记录完整文本）
  recordTextInput(element, finalValue) {
    const selector = getCSSSelector(element);
    const xpath = getXPath(element);
    const inputType = element.type || 'text';
    
    // 如果是之前记录过的输入框，更新而不是新增
    const existingActionIndex = this.actions.findIndex(action => 
      action.type === 'input_text' && 
      action.data.parameters.selector === selector
    );

    const inputAction = {
      label: `输入文本到 ${element.tagName}${element.id ? '#' + element.id : ''}`,
      parameters: {
        selector: selector,
        selectorType: 'css',
        xpath: xpath,
        text: finalValue,
        clearBefore: true,
        inputType: inputType === 'password' ? 'password' : 'type',
        pressEnter: false
      }
    };

    if (existingActionIndex >= 0) {
      // 更新现有动作，保持原有时间戳以维持正确顺序
      this.actions[existingActionIndex].data = inputAction;
    } else {
      // 检查是否有对应的点击记录
      const clickRecord = this.pendingInputClicks.get(element);
      
              if (clickRecord) {
         // 有点击记录：忽略激活点击，只记录输入操作
         
         // 使用点击时间作为输入操作的时间戳（保持操作的连贯性）
         const actionTime = clickRecord.timestamp;
         const timeSinceStart = actionTime - this.startTime;
         const timeSinceLastAction = actionTime - this.lastActionTime;
         
         const inputActionData = {
           id: `input_text-${this.nodeCounter++}`,
           type: 'input_text',
           timestamp: timeSinceStart,
           delay: timeSinceLastAction,
           data: inputAction,
           url: window.location.href
         };
         
         this.actions.push(inputActionData);
         this.lastActionTime = actionTime;
         
         // 发送输入动作
         sendEvent({
           type: 'workflow_action_recorded',
           action: inputActionData,
           totalActions: this.actions.length
         });
         
         console.log('录制输入操作（忽略激活点击）:', inputActionData);
         
         // 清理点击记录
         this.pendingInputClicks.delete(element);
        
      } else {
        // 没有点击记录：只记录输入
        const inputStartTime = this.pendingInputs.get(element) || Date.now();
        const timeSinceStart = inputStartTime - this.startTime;
        const timeSinceLastAction = inputStartTime - this.lastActionTime;

        const action = {
          id: `input_text-${this.nodeCounter++}`,
          type: 'input_text',
          timestamp: timeSinceStart,
          delay: timeSinceLastAction,
          data: inputAction,
          url: window.location.href
        };

        // 插入到正确的位置以保持时间顺序
        const insertIndex = this.actions.findIndex(a => a.timestamp > timeSinceStart);
        if (insertIndex >= 0) {
          this.actions.splice(insertIndex, 0, action);
        } else {
          this.actions.push(action);
        }

        // 发送到侧边栏显示
        sendEvent({
          type: 'workflow_action_recorded',
          action: action,
          totalActions: this.actions.length
        });

        console.log('录制纯输入动作:', action);
      }
    }
  }

  // 处理下拉选择
  recordSelectOption(element, selectedValue, selectedText) {
    const selector = getCSSSelector(element);
    const xpath = getXPath(element);
    
    this.addAction('select_option', {
      label: `选择选项: ${selectedText}`,
      parameters: {
        selector: selector,
        selectorType: 'css',
        xpath: xpath,
        value: selectedValue,
        text: selectedText,
        selectBy: 'value'
      }
    });
  }

  // 处理滚动事件
  recordScroll(scrollX, scrollY) {
    // 防止过于频繁的滚动记录
    const lastAction = this.actions[this.actions.length - 1];
    if (lastAction && lastAction.type === 'scroll' && 
        Date.now() - this.lastActionTime < 1000) {
      // 更新最后的滚动动作
      lastAction.data.parameters.x = scrollX;
      lastAction.data.parameters.y = scrollY;
      lastAction.timestamp = Date.now() - this.startTime;
      return;
    }

    this.addAction('scroll', {
      label: `滚动到位置 (${scrollX}, ${scrollY})`,
      parameters: {
        scrollType: 'by_pixels',
        x: scrollX,
        y: scrollY,
        smooth: true
      }
    });
  }

  // 生成符合规范的工作流JSON
  generateWorkflowJSON() {
    const nodes = [];
    const edges = [];
    let lastNodeId = null;

    // 按时间戳排序确保正确的执行顺序
    const sortedActions = [...this.actions].sort((a, b) => a.timestamp - b.timestamp);

    sortedActions.forEach((action, index) => {
      const node = {
        id: action.id,
        type: action.type,
        position: { x: 100 + (index * 200), y: 100 },
        data: action.data
      };
      nodes.push(node);

      // 创建连接
      if (lastNodeId) {
        edges.push({
          id: `edge-${index}`,
          source: lastNodeId,
          target: action.id,
          sourceHandle: 'success',
          targetHandle: 'input',
          data: {
            condition: 'always',
            delay: Math.min(action.delay, 5000) // 限制最大延迟
          }
        });
      }

      lastNodeId = action.id;
    });

    return {
      id: `workflow-recorded-${Date.now()}`,
      name: `录制的工作流 - ${new Date().toLocaleString()}`,
      description: `自动录制于 ${window.location.href}`,
      version: '1.0.0',
      variables: {
        baseUrl: window.location.origin,
        recordedAt: new Date().toISOString()
      },
      nodes: nodes,
      edges: edges,
      metadata: {
        recordStartTime: this.startTime,
        recordEndTime: Date.now(),
        totalDuration: Date.now() - this.startTime,
        actionsCount: this.actions.length,
        recordedUrl: this.currentUrl
      }
    };
  }

  // 清空录制数据
  clear() {
    this.actions = [];
    this.startTime = Date.now();
    this.lastActionTime = this.startTime;
    this.nodeCounter = 1;
    this.formInputs.clear();
    this.pendingInputs.clear();
    this.pendingInputClicks.clear();
  }
}

// 数据提取器类
class DataExtractor {
  constructor() {
    this.selectedTable = null;
    this.fields = [];
    this.extractedData = [];
    this.isExtracting = false;
  }

  // 智能检测表格结构
  detectTableStructure(element) {
    const result = {
      type: 'unknown',
      container: element,
      rows: [],
      suggestedFields: []
    };

    // 1. 检测HTML表格
    if (element.tagName === 'TABLE') {
      result.type = 'html-table';
      const rows = element.querySelectorAll('tr');
      result.rows = Array.from(rows).slice(1); // 排除表头
      
      // 从表头推导字段
      const headerRow = element.querySelector('tr');
      if (headerRow) {
        const headers = headerRow.querySelectorAll('th, td');
        result.suggestedFields = Array.from(headers).map((header, index) => ({
          name: header.textContent.trim() || `列${index + 1}`,
          selector: `td:nth-child(${index + 1})`,
          type: 'text'
        }));
      }
    }
    // 2. 检测重复的div结构（如商品列表）
    else if (this.hasRepeatingStructure(element)) {
      result.type = 'repeating-divs';
      result.rows = this.findRepeatingItems(element);
      result.suggestedFields = this.suggestFieldsFromStructure(result.rows[0]);
    }
    // 3. 检测列表结构
    else if (element.tagName === 'UL' || element.tagName === 'OL') {
      result.type = 'list';
      result.rows = Array.from(element.querySelectorAll('li'));
      result.suggestedFields = this.suggestFieldsFromStructure(result.rows[0]);
    }
    // 4. 通用容器检测
    else {
      const childElements = Array.from(element.children);
      if (childElements.length > 1) {
        result.type = 'container';
        result.rows = childElements;
        result.suggestedFields = this.suggestFieldsFromStructure(result.rows[0]);
      }
    }

    return result;
  }

  // 检测是否有重复结构
  hasRepeatingStructure(element) {
    const children = Array.from(element.children);
    if (children.length < 2) return false;

    // 检查前几个子元素是否有相似的结构
    const firstChild = children[0];
    const similarCount = children.slice(1, Math.min(5, children.length)).filter(child => {
      return this.isSimilarStructure(firstChild, child);
    }).length;

    return similarCount >= Math.min(2, children.length - 1);
  }

  // 判断两个元素是否有相似结构
  isSimilarStructure(elem1, elem2) {
    if (elem1.tagName !== elem2.tagName) return false;
    if (elem1.children.length !== elem2.children.length) return false;
    
    // 检查子元素的标签结构
    for (let i = 0; i < elem1.children.length; i++) {
      if (elem1.children[i].tagName !== elem2.children[i].tagName) {
        return false;
      }
    }
    
    return true;
  }

  // 找到重复的项目
  findRepeatingItems(container) {
    const children = Array.from(container.children);
    if (children.length === 0) return [];

    const firstChild = children[0];
    const similarItems = [firstChild];

    for (let i = 1; i < children.length; i++) {
      if (this.isSimilarStructure(firstChild, children[i])) {
        similarItems.push(children[i]);
      }
    }

    return similarItems;
  }

  // 从结构中推导字段
  suggestFieldsFromStructure(sampleElement) {
    if (!sampleElement) return [];

    const fields = [];
    const textElements = [];
    const linkElements = [];
    const imageElements = [];

    // 递归查找有用的元素
    const findUsefulElements = (element, depth = 0) => {
      if (depth > 3) return; // 限制递归深度

      // 文本内容
      if (element.textContent && element.textContent.trim() && 
          element.children.length === 0) {
        textElements.push(element);
      }

      // 链接
      if (element.tagName === 'A' && element.href) {
        linkElements.push(element);
      }

      // 图片
      if (element.tagName === 'IMG' && element.src) {
        imageElements.push(element);
      }

      // 递归检查子元素
      Array.from(element.children).forEach(child => {
        findUsefulElements(child, depth + 1);
      });
    };

    findUsefulElements(sampleElement);

    // 生成字段建议
    textElements.forEach((elem, index) => {
      const text = elem.textContent.trim();
      if (text.length > 0 && text.length < 100) {
        fields.push({
          name: this.guessFieldName(text) || `文本${index + 1}`,
          selector: this.generateRelativeSelector(elem, sampleElement),
          type: this.guessDataType(text)
        });
      }
    });

    linkElements.forEach((elem, index) => {
      fields.push({
        name: `链接${index + 1}`,
        selector: this.generateRelativeSelector(elem, sampleElement),
        type: 'href'
      });
    });

    imageElements.forEach((elem, index) => {
      fields.push({
        name: `图片${index + 1}`,
        selector: this.generateRelativeSelector(elem, sampleElement),
        type: 'src'
      });
    });

    return fields.slice(0, 8); // 限制字段数量
  }

  // 猜测字段名称
  guessFieldName(text) {
    const cleanText = text.toLowerCase().trim();
    
    if (cleanText.includes('价格') || cleanText.includes('¥') || cleanText.includes('$')) {
      return '价格';
    }
    if (cleanText.includes('标题') || cleanText.includes('名称')) {
      return '标题';
    }
    if (cleanText.includes('时间') || cleanText.includes('日期')) {
      return '时间';
    }
    if (cleanText.includes('评分') || cleanText.includes('★') || cleanText.includes('⭐')) {
      return '评分';
    }
    
    return text.length > 20 ? text.substring(0, 10) + '...' : text;
  }

  // 猜测数据类型
  guessDataType(text) {
    if (/^\d+(\.\d+)?$/.test(text)) return 'number';
    if (/¥|￥|\$|USD|CNY/.test(text)) return 'price';
    if (/\d{4}-\d{2}-\d{2}|\d{2}\/\d{2}\/\d{4}/.test(text)) return 'date';
    if (/★|⭐|评分|分数/.test(text)) return 'rating';
    return 'text';
  }

  // 生成相对于容器的选择器
  generateRelativeSelector(element, container) {
    const path = [];
    let current = element;

    while (current && current !== container && current.parentElement) {
      let selector = current.tagName.toLowerCase();
      
      // 添加类名
      if (current.className && typeof current.className === 'string') {
        const classes = current.className.split(' ').filter(c => c.trim());
        if (classes.length > 0) {
          selector += '.' + classes[0];
        }
      }
      
      // 添加索引
      const siblings = Array.from(current.parentElement.children).filter(
        sibling => sibling.tagName === current.tagName
      );
      if (siblings.length > 1) {
        const index = siblings.indexOf(current);
        selector += `:nth-of-type(${index + 1})`;
      }

      path.unshift(selector);
      current = current.parentElement;
    }

    return path.join(' > ');
  }

  // 提取数据
  async extractData(progressCallback) {
    if (!this.selectedTable || this.fields.length === 0) {
      throw new Error('请先选择表格并配置字段');
    }

    this.isExtracting = true;
    this.extractedData = [];

    const structure = this.detectTableStructure(this.selectedTable);
    const rows = structure.rows;

    console.log('开始提取数据:', {
      tableType: structure.type,
      rowCount: rows.length,
      fieldCount: this.fields.length
    });

    for (let i = 0; i < rows.length; i++) {
      const row = rows[i];
      const rowData = {};

      // 提取每个字段的数据
      this.fields.forEach(field => {
        if (field.enabled) {
          try {
            rowData[field.name] = this.extractFieldValue(row, field);
          } catch (error) {
            console.warn(`提取字段 ${field.name} 失败:`, error);
            rowData[field.name] = '';
          }
        }
      });

      this.extractedData.push(rowData);

      // 进度回调
      if (progressCallback) {
        progressCallback({
          current: i + 1,
          total: rows.length,
          percentage: Math.round(((i + 1) / rows.length) * 100)
        });
      }

      // 避免阻塞UI
      if (i % 10 === 0) {
        await new Promise(resolve => setTimeout(resolve, 1));
      }
    }

    this.isExtracting = false;
    
    console.log('数据提取完成:', {
      extractedRows: this.extractedData.length,
      sampleData: this.extractedData.slice(0, 3)
    });

    return this.extractedData;
  }

  // 提取字段值
  extractFieldValue(rowElement, field) {
    const element = rowElement.querySelector(field.selector);
    if (!element) return '';

    switch (field.type) {
      case 'text':
        return element.textContent?.trim() || '';
      case 'href':
        return element.href || element.getAttribute('href') || '';
      case 'src':
        return element.src || element.getAttribute('src') || '';
      case 'number':
        const numText = element.textContent?.trim() || '';
        const num = parseFloat(numText.replace(/[^\d.-]/g, ''));
        return isNaN(num) ? '' : num;
      case 'price':
        const priceText = element.textContent?.trim() || '';
        const price = parseFloat(priceText.replace(/[^\d.-]/g, ''));
        return isNaN(price) ? priceText : price;
      default:
        return element.textContent?.trim() || '';
    }
  }

  // 设置字段配置
  setFields(fields) {
    this.fields = fields;
  }

  // 设置选中的表格
  setSelectedTable(element) {
    this.selectedTable = element;
  }

  // 清空数据
  clear() {
    this.selectedTable = null;
    this.fields = [];
    this.extractedData = [];
    this.isExtracting = false;
  }

  // 获取提取的数据
  getExtractedData() {
    return this.extractedData;
  }
}

// 检查扩展上下文是否有效
function checkExtensionContext() {
  try {
    if (chrome.runtime && chrome.runtime.id) {
      return true;
    }
  } catch (error) {
    console.log('扩展上下文已失效');
    isExtensionValid = false;
    return false;
  }
  return false;
}

function sendEvent(data) {
  if (!checkExtensionContext()) {
    console.log('扩展上下文无效，停止发送事件');
    return;
  }

  try {
    console.log('发送事件:', data);
    chrome.runtime.sendMessage(data).catch((error) => {
      if (error.message.includes('Extension context invalidated')) {
        console.log('扩展上下文已失效，停止监听');
        isExtensionValid = false;
        removeEventListeners();
      } else {
        console.log('发送消息失败:', error.message);
      }
    });
  } catch (error) {
    console.log('发送消息异常:', error.message);
    isExtensionValid = false;
  }
}

// 创建悬浮高亮覆盖层
function createHighlightOverlay() {
  if (hoverHighlight) return hoverHighlight;
  
  hoverHighlight = document.createElement('div');
  hoverHighlight.id = 'automa-hover-highlight';
  hoverHighlight.style.cssText = `
    position: absolute !important;
    pointer-events: none !important;
    z-index: 999999 !important;
    border: 2px solid #007bff !important;
    background: rgba(0, 123, 255, 0.1) !important;
    border-radius: 3px !important;
    box-shadow: 0 0 10px rgba(0, 123, 255, 0.5) !important;
    transition: all 0.1s ease !important;
    display: none !important;
  `;
  
  document.body.appendChild(hoverHighlight);
  return hoverHighlight;
}

// 高亮元素
function highlightElement(element) {
  if (!element || !hoverHighlight) return;
  
  const rect = element.getBoundingClientRect();
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
  
  hoverHighlight.style.cssText += `
    display: block !important;
    left: ${rect.left + scrollLeft}px !important;
    top: ${rect.top + scrollTop}px !important;
    width: ${rect.width}px !important;
    height: ${rect.height}px !important;
  `;
}

// 隐藏高亮
function hideHighlight() {
  if (hoverHighlight) {
    hoverHighlight.style.display = 'none';
  }
}

// 悬浮处理器 - 只高亮，不发送事件
function handleMouseOver(e) {
  if (!isExtensionValid || (!isHoverMode && !isRecordingMode && !isDataExtractionMode)) return;
  
  const target = e.target;
  
  // 忽略我们创建的元素
  if (target.id === 'automa-hover-highlight') return;
  
  currentHoveredElement = target;
  
  // 创建并显示高亮
  createHighlightOverlay();
  highlightElement(target);
}

// 鼠标离开处理器
function handleMouseOut(e) {
  if (!isExtensionValid || (!isHoverMode && !isRecordingMode && !isDataExtractionMode)) return;
  
  // 如果鼠标移到了子元素上，不隐藏高亮
  if (e.relatedTarget && currentHoveredElement && currentHoveredElement.contains(e.relatedTarget)) {
    return;
  }
  
  // 延迟隐藏，避免快速移动时闪烁
  setTimeout(() => {
    if (!currentHoveredElement || !currentHoveredElement.matches(':hover')) {
      hideHighlight();
      currentHoveredElement = null;
    }
  }, 50);
}

// 点击处理器
function handleClick(e) {
  if (!isExtensionValid) return;
  
  const target = e.target;
  
  // 忽略我们创建的元素
  if (target.id === 'automa-hover-highlight') return;
  
  // 选择器模式：点击捕获选择器
  if (isHoverMode) {
    const clickData = {
      type: 'selector_captured',
      time: new Date().toLocaleTimeString(),
      tag: target.tagName,
      id: target.id || '无',
      class: target.className || '无',
      text: target.textContent.trim().substring(0, 50),
      value: target.value ? `输入值: ${target.value}` : '',
      xpath: getXPath(target),
      cssSelector: getCSSSelector(target)
    };
    
    sendEvent(clickData);
    
    // 阻止默认行为
    e.preventDefault();
    e.stopPropagation();
    return false;
  }
  
  // 录制模式：记录点击动作
  if (isRecordingMode && workflowRecorder) {
    workflowRecorder.recordClick(target, e);
    
    // 如果点击的是提交按钮或链接，可能触发页面跳转
    // 但不立即记录导航，让导航过滤逻辑来处理
    if (target.type === 'submit' || target.tagName === 'A') {
      // 不再主动记录导航，由页面导航事件自然触发
      console.log('点击了可能导致导航的元素，等待自然导航事件');
    }
  }

  // 数据抓取模式：选择表格容器
  if (isDataExtractionMode) {
    if (!dataExtractor) {
      dataExtractor = new DataExtractor();
    }

    // 设置选中的表格
    dataExtractor.setSelectedTable(target);
    
    // 检测表格结构
    const structure = dataExtractor.detectTableStructure(target);
    
    sendEvent({
      type: 'table_selected',
      time: new Date().toLocaleTimeString(),
      tableInfo: {
        type: structure.type,
        rowCount: structure.rows.length,
        selector: getCSSSelector(target),
        xpath: getXPath(target),
        suggestedFields: structure.suggestedFields
      }
    });

    // 阻止默认行为
    e.preventDefault();
    e.stopPropagation();
    return false;
  }
}

// 智能文本输入处理
function handleInputFocus(e) {
  if (!isRecordingMode || !workflowRecorder) return;
  
  const target = e.target;
  if (!isFormInputElement(target)) return;
  
  // 记录初始值和输入开始时间
  workflowRecorder.formInputs.set(target, target.value);
  workflowRecorder.pendingInputs.set(target, Date.now());
  
  // 不再自动删除点击记录，保留到输入完成时一起处理
}

function handleInputBlur(e) {
  if (!isRecordingMode || !workflowRecorder) return;
  
  const target = e.target;
  if (!isFormInputElement(target)) return;
  
  const initialValue = workflowRecorder.formInputs.get(target) || '';
  const finalValue = target.value;
  
  // 只有当值确实改变时才记录
  if (finalValue !== initialValue) {
    workflowRecorder.recordTextInput(target, finalValue);
  }
  
  workflowRecorder.formInputs.delete(target);
  workflowRecorder.pendingInputs.delete(target);
}

function handleSelectChange(e) {
  if (!isRecordingMode || !workflowRecorder) return;
  
  const target = e.target;
  if (target.tagName !== 'SELECT') return;
  
  const selectedOption = target.options[target.selectedIndex];
  if (selectedOption) {
    workflowRecorder.recordSelectOption(
      target,
      selectedOption.value,
      selectedOption.text
    );
  }
}

// 滚动处理
function handleScroll(e) {
  if (!isRecordingMode || !workflowRecorder) return;
  
  // 节流处理，避免过于频繁的滚动记录
  clearTimeout(handleScroll.scrollTimer);
  handleScroll.scrollTimer = setTimeout(() => {
    workflowRecorder.recordScroll(window.scrollX, window.scrollY);
  }, 300);
}

// 检查是否是表单输入元素
function isFormInputElement(element) {
  const inputTypes = ['text', 'email', 'password', 'search', 'tel', 'url', 'number'];
  return (
    (element.tagName === 'INPUT' && inputTypes.includes(element.type)) ||
    element.tagName === 'TEXTAREA'
  );
}

// 键盘处理器 - 只处理ESC键
function handleKeydown(e) {
  if (!isExtensionValid) return;
  
  // ESC键退出悬浮模式或录制模式
  if (e.key === 'Escape') {
    if (isHoverMode) {
      toggleHoverMode(false);
      e.preventDefault();
      return false;
    }
    if (isRecordingMode) {
      toggleRecordingMode(false);
      e.preventDefault();
      return false;
    }
  }
}

// 切换悬浮模式
function toggleHoverMode(enable) {
  isHoverMode = enable;

  if (enable) {
    // 如果正在录制，先停止录制
    if (isRecordingMode) {
      toggleRecordingMode(false);
    }
    // 如果正在数据抓取，先停止
    if (isDataExtractionMode) {
      toggleDataExtractionMode(false);
    }

    document.body.style.cursor = 'crosshair !important';
    createHighlightOverlay();
    sendEvent({ type: 'hover_mode_on', time: new Date().toLocaleTimeString() });
  } else {
    document.body.style.cursor = '';
    hideHighlight();
    currentHoveredElement = null;
    sendEvent({ type: 'hover_mode_off', time: new Date().toLocaleTimeString() });
  }
}

// 页面导航监听器
// let lastUrl = window.location.href; // 已在开头声明
function checkForNavigation() {
  if (!isRecordingMode || !workflowRecorder) return;
  
  const currentUrl = window.location.href;
  if (currentUrl !== lastUrl) {
    // 传递isInitialNavigation = false，让recordNavigation函数进行过滤判断
    workflowRecorder.recordNavigation(currentUrl, false);
    lastUrl = currentUrl;
  }
}

// 切换录制模式
function toggleRecordingMode(enable) {
  isRecordingMode = enable;
  
  if (enable) {
    // 如果正在选择，先停止选择
    if (isHoverMode) {
      toggleHoverMode(false);
    }
    // 如果正在数据抓取，先停止
    if (isDataExtractionMode) {
      toggleDataExtractionMode(false);
    }
    
    // 初始化录制器
    workflowRecorder = new WorkflowRecorder();
    
    // 记录当前页面作为起始点
    lastUrl = window.location.href;
    workflowRecorder.recordNavigation(lastUrl, true);
    
    // 开始监听导航变化
    const navigationInterval = setInterval(() => {
      if (!isRecordingMode) {
        clearInterval(navigationInterval);
        return;
      }
      checkForNavigation();
    }, 500);
    
    document.body.style.cursor = 'copy !important';
    createHighlightOverlay();
    sendEvent({ type: 'recording_mode_on', time: new Date().toLocaleTimeString() });
  } else {
    document.body.style.cursor = '';
    hideHighlight();
    currentHoveredElement = null;
    
    if (workflowRecorder) {
      // 发送完整的工作流数据
      const workflowJSON = workflowRecorder.generateWorkflowJSON();
      sendEvent({ 
        type: 'recording_mode_off', 
        time: new Date().toLocaleTimeString(),
        workflowData: workflowJSON
      });
    }
  }
}

// 切换数据抓取模式
function toggleDataExtractionMode(enable) {
  isDataExtractionMode = enable;

  if (enable) {
    // 如果正在选择，先停止选择
    if (isHoverMode) {
      toggleHoverMode(false);
    }
    // 如果正在录制，先停止录制
    if (isRecordingMode) {
      toggleRecordingMode(false);
    }

    // 初始化数据提取器
    if (!dataExtractor) {
      dataExtractor = new DataExtractor();
    }

    document.body.style.cursor = 'pointer !important';
    createHighlightOverlay();
    sendEvent({ type: 'data_extraction_mode_on', time: new Date().toLocaleTimeString() });
  } else {
    document.body.style.cursor = '';
    hideHighlight();
    currentHoveredElement = null;
    sendEvent({ type: 'data_extraction_mode_off', time: new Date().toLocaleTimeString() });
  }
}

// 获取元素的 XPath
function getXPath(el) {
  if (!el) return '';
  if (el.id) return `//*[@id="${el.id}"]`;
  
  const parts = [];
  while (el && el.nodeType === Node.ELEMENT_NODE) {
    let nb = 0;
    let sibling = el.previousSibling;
    while (sibling) {
      if (sibling.nodeType === Node.ELEMENT_NODE && sibling.nodeName === el.nodeName) {
        nb++;
      }
      sibling = sibling.previousSibling;
    }
    
    const nodeName = el.nodeName.toLowerCase();
    const index = nb > 0 ? `[${nb + 1}]` : '';
    parts.unshift(nodeName + index);
    el = el.parentNode;
  }
  
  return parts.length ? '/' + parts.join('/') : '';
}

// 获取元素的 CSS 选择器
function getCSSSelector(el) {
  if (!el) return '';
  if (el.id) return `#${el.id}`;
  
  const path = [];
  while (el && el.nodeType === Node.ELEMENT_NODE) {
    let selector = el.nodeName.toLowerCase();
    
    if (el.id) {
      selector = `#${el.id}`;
      path.unshift(selector);
      break;
    }
    
    if (el.className && typeof el.className === 'string') {
      const classes = el.className.split(' ').filter(c => c.trim());
      if (classes.length > 0) {
        selector += '.' + classes[0];
      }
    }
    
    if (el.parentNode) {
      const siblings = Array.from(el.parentNode.children).filter(sibling => 
        sibling.nodeName === el.nodeName
      );
      if (siblings.length > 1) {
        const index = siblings.indexOf(el) + 1;
        selector += `:nth-child(${index})`;
      }
    }
    
    path.unshift(selector);
    el = el.parentNode;
  }
  
  return path.join(' > ');
}

// 事件监听器管理
function addEventListeners() {
  if (!isExtensionValid) return;
  
  // 基础事件
  document.addEventListener('click', handleClick, true);
  document.addEventListener('keydown', handleKeydown, true);
  document.addEventListener('mouseover', handleMouseOver, true);
  document.addEventListener('mouseout', handleMouseOut, true);
  
  // 录制相关事件
  document.addEventListener('focus', handleInputFocus, true);
  document.addEventListener('blur', handleInputBlur, true);
  document.addEventListener('change', handleSelectChange, true);
  window.addEventListener('scroll', handleScroll, { passive: true });
  
  console.log('Automa风格选择器+录制监听器已添加');
}

function removeEventListeners() {
  document.removeEventListener('click', handleClick, true);
  document.removeEventListener('keydown', handleKeydown, true);
  document.removeEventListener('mouseover', handleMouseOver, true);
  document.removeEventListener('mouseout', handleMouseOut, true);
  
  // 移除录制事件
  document.removeEventListener('focus', handleInputFocus, true);
  document.removeEventListener('blur', handleInputBlur, true);
  document.removeEventListener('change', handleSelectChange, true);
  window.removeEventListener('scroll', handleScroll);
  
  // 清理创建的元素
  if (hoverHighlight) {
    hoverHighlight.remove();
    hoverHighlight = null;
  }
  
  // 恢复光标
  document.body.style.cursor = '';
  isHoverMode = false;
  isRecordingMode = false;
  
  console.log('选择器+录制监听器已移除');
}

// 监听来自background的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'toggleHoverMode') {
    toggleHoverMode(message.enable);
    sendResponse({ success: true });
  } else if (message.action === 'toggleRecordingMode') {
    toggleRecordingMode(message.enable);
    sendResponse({ success: true });
  } else if (message.action === 'toggleDataExtractionMode') {
    toggleDataExtractionMode(message.enable);
    sendResponse({ success: true });
  } else if (message.action === 'getWorkflowData') {
    const data = workflowRecorder ? workflowRecorder.generateWorkflowJSON() : null;
    sendResponse({ workflowData: data });
  } else if (message.action === 'setExtractionFields') {
    if (dataExtractor) {
      dataExtractor.setFields(message.fields);
      sendResponse({ success: true });
    } else {
      sendResponse({ success: false, error: '数据提取器未初始化' });
    }
  } else if (message.action === 'startDataExtraction') {
    if (dataExtractor) {
      dataExtractor.extractData((progress) => {
        sendEvent({
          type: 'extraction_progress',
          progress: progress
        });
      }).then(data => {
        sendEvent({
          type: 'extraction_complete',
          data: data,
          time: new Date().toLocaleTimeString()
        });
      }).catch(error => {
        sendEvent({
          type: 'extraction_error',
          error: error.message,
          time: new Date().toLocaleTimeString()
        });
      });
      sendResponse({ success: true });
    } else {
      sendResponse({ success: false, error: '数据提取器未初始化' });
    }
  }
});

// 页面卸载前清理
window.addEventListener('beforeunload', removeEventListeners);

// 初始化
addEventListeners();
console.log('🎯 Automa风格选择器+工作流录制脚本已加载'); 